package com.lk.netty.handler;

import com.lk.netty.EchoClient;
import com.lk.netty.encode.UserMessageDecode;
import com.lk.netty.encode.UserMessageEncode;
import com.lk.netty.initializer.ProxyToServerIniializer;
import com.lk.netty.session.SessionFactory;
import io.netty.bootstrap.Bootstrap;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

import java.util.Map;

// 自定义的 ChannelHandler 处理器
public class ServerHandler extends ChannelInboundHandlerAdapter {

    private Channel outboundChannel;

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {

        Channel inboundChannel = ctx.channel();

        if (msg instanceof ByteBuf) {
            if (null == msg) {
                inboundChannel.writeAndFlush(msg).addListener(new ChannelFutureListener() {
                    @Override
                    public void operationComplete(ChannelFuture future) {
                        if (future.isSuccess()) {
                            ctx.channel().read();
                        } else {
                            future.channel().close();
                        }
                    }
                });
            }else{
                outboundChannel.writeAndFlush(msg).addListener(new ChannelFutureListener() {
                    @Override
                    public void operationComplete(ChannelFuture future) {
                        if (future.isSuccess()) {
                            // was able to flush out data, start to read the next chunk
                            ctx.channel().read();
                        } else {
                            future.channel().close();
                        }
                    }
                });
            }
        }

//
//        String cid = new String(bytes);
//        SessionFactory.getChannel("");
//
//        System.out.println("服务端返回消息");
//        String msg2 = "hello client!";
//        ByteBuf encoded = ctx.alloc().buffer(4 * msg2.length());
//        encoded.writeBytes(msg2.getBytes());
//
//        ctx.write(encoded);
//        ctx.flush();
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        System.out.println("servre: channelReadComplete");
        super.channelReadComplete(ctx);
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws InterruptedException {

        EventLoopGroup group = new NioEventLoopGroup();
        final Channel inboundChannel = ctx.channel();

        Bootstrap b = new Bootstrap();
        b.group(group)
                .channel(ctx.channel().getClass())
                .handler(new ProxyToServerIniializer(inboundChannel))
                .option(ChannelOption.AUTO_READ, false);

        ChannelFuture f = b.connect("127.0.0.1", 3306);
        outboundChannel = f.channel();

        f.addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) {
                if (future.isSuccess()) {
                    inboundChannel.read();
                } else {
                    inboundChannel.close();
                }
            }
        });
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        cause.printStackTrace();
        ctx.close(); // 发生异常时关闭连接
    }

    static void closeOnFlush(Channel ch) {
        if (ch.isActive()) {
            ch.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE);
        }
    }

}